<template>
	<view>
		<u-loading-page bg-color="#fff" :loading="pageLoading" textSize="8"></u-loading-page>
		<!-- 物资采购计划 -->
		<view class="container-box" v-if="!pageLoading">
			<view class="pl-30">
				<sub-title>基本信息</sub-title>
			</view>
			<view class="pl-30 pr-30">
				<u--form labelPosition="left" labelWidth="80" :model="formData" class="pl-30 pr-30"
					:labelStyle="{fontSize: '28rpx'}">
					<u-form-item v-for="(item, i) in mapData" :key="i" :label="item.name" :borderBottom="true"
						@click="taxRateShow(['增值税税率'].indexOf(item[0])!=-1)">
						<u--textarea v-if="['备注'].indexOf(item.name)!=-1" confirmType="done" @linechange="(val)=>{
								lineCount = val.detail.lineCount
							}" :autoHeight="true" :class="{projectclass: true,oneLine: lineCount==1}" v-model="formData[item.label]"
							:disabled="true" border="none">
						</u--textarea>
						<u--input v-else :value="formData[item.label]" border="none" inputAlign="right" readonly />
						<u-icon v-if="['增值税税率'].indexOf(item[0])!=-1" slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</u--form>
			</view>
			<!-- 明细信息 -->
			<view class="space" />
			<view class="pl-30 pt-30">
				<sub-title>明细信息</sub-title>
			</view>
			<view class="ml-30 mr-30 mb-30 mt-30 collapse-box">
				<u-collapse accordion :border="false" value="0">
					<u-collapse-item :name="i" title="物资名称" v-for="(ite, i) in formData.productList" :key="i" class="mb-20">
						<text slot="value" class="u-page__item__title__slot-title">{{ite.materialNameDictLabel}}</text>
						<u--form labelPosition="left" labelWidth="160" :labelStyle="{fontSize: '28rpx'}">
							<u-form-item v-for="(it, ind) in column" :label="it.label"
								:borderBottom="ind==column.length-1?false:true" :labelWidth="it.label!='备注'?'160':'80'"
								:key="ind">
								<u--textarea v-if="['备注'].indexOf(it.label)!=-1" confirmType="done"
									@linechange="(val)=>{ lineCount2 = val.detail.lineCount}" :autoHeight="true"
									:class="{projectclass: true,oneLine: lineCount2==1}" v-model="ite[it.key]" :disabled="true"
									border="none">
								</u--textarea>
								<u--input v-else :value="ite[it.key]" border="none" inputAlign="right" readonly>
								</u--input>
							</u-form-item>
						</u--form>
					</u-collapse-item>
				</u-collapse>
			</view>
			<!-- 审批 -->
			<view class="space" v-if="fromTab==0" />
			<view class="pl-30 pt-30">
				<sub-title v-if="fromTab==0">审批</sub-title>
			</view>
			<u--form v-if="fromTab==0" :model="approvalForm" ref="approvalForm" :rules="rules" class="approval-form">
				<view class="pl-30 pt-30 pr-30 pb-30">
					<view class="pb-30 fs-28">审批结果</view>
					<view class="pb-30" style="border-bottom: 1px solid #dee2eb;">
						<u-radio-group v-model="approvalForm.type" @change="groupChange" class="group-text" size="24">
							<u-radio shape="circle" label="通过" name="1" />
							<u-radio :customStyle="{marginLeft: '36rpx',fontSize: '20rpx'}" shape="circle" label="退回" name="2"
								v-if="stepActive !== 1" />
							<u-radio :customStyle="{marginLeft: '36rpx'}" shape="circle" label="驳回" name="3" />
						</u-radio-group>
					</view>
				</view>
				<view class="pl-30 pr-30 pb-30" v-if="approvalForm.type==2">
					<view class="pb-30 fs-28">退回节点</view>
					<view class="pb-30" style="border-bottom: 1px solid #dee2eb;">
						<view @click="nodeInputHandler"
							style="display: flex;align-items: center;font-size: 28rpx;color: #C8CBD2;border: 1rpx solid #EAEAEA;padding: 10rpx;">
							{{approvalForm.returnNodeName||'请选择退回节点'}}
						</view>
					</view>
				</view>
				<view class="pl-30 pr-30 pb-10">
					<view class="pb-30 fs-28">审批意见</view>
					<u--textarea confirmType="done" v-model="approvalForm.comment" maxlength="255" :count="true"
						placeholder="请输入审批意见"></u--textarea>
				</view>
			</u--form>
			<u-picker :show="showPicker" :closeOnClickOverlay="true" :columns="returnsList" @confirm="confirmPicker"
				@close="closePicker" @cancel="closePicker" keyName="name"></u-picker>
			<!-- 审批记录 -->
			<view class="space" />
			<approval-records class="ml-30 mr-30 pt-30" :flowList="flowList" />
			<!-- 提交审批 -->
			<view class="fix-btn" id="fixB" v-if="fromTab==0">
				<u-button type="primary" size="small" text="提交" color="#2289FF" class="btnB fs-28" @click="submitForm"
					:loading="loading"></u-button>
			</view>
		</view>
		<!-- 增值税率 -->
		<u-picker :show="showtaxRate" keyName="dictLabel" @confirm="taxRate" :columns="tax_rate"
			@cancel="showtaxRate=false">
		</u-picker>
	</view>
</template>

<script>
	import SubTitle from '@/pagesIndex/component/SubTitle.vue'
	import InfoCard from '@/pagesIndex/component/InfoCard.vue'
	import FileUpload from '@/components/fileUpload.vue'
	import ApprovalRecords from '@/pagesIndex/contractManagement/approvelRecords.vue'
	export default {
		components: {
			SubTitle,
			FileUpload,
			InfoCard,
			ApprovalRecords
		},
		data() {
			const checkApprovalType = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					callback(new Error('请选择审批结果'))
				}
			}
			const checkApprovalComment = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					callback(new Error('请输入审批意见'))
				}
			}
			const checkApprovalTargetKey = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					if (this.approvalForm.type != 2) {
						callback()
					} else {
						callback(new Error('请选择退回节点'))
					}
				}
			}
			return {
				pageLoading: false,
				screenHeight: undefined,
				originalHeight: undefined,
				fromTab: 1, //判断是从【待办，已办】哪个tab页面进行的跳转  待办中跳转都能进行审批，已办只能查看详情
				detailId: undefined,
				loading: false,
				lineCount: 0,
				lineCount2: 0,
				// 基本信息
				mapData: [{
						name: '业务单号',
						label: 'reviewCode'
					},
					{
						name: '项目名称',
						label: 'projectName'
					},
					{
						name: '物资类型',
						label: 'materialTypeDictLabel'
					},
					{
						name: '采购时间',
						label: 'purchaseTime'
					},
					{
						name: '增值税税率',
						label: 'vatRateDictLabel'
					},
					{
						name: '含税合计',
						label: 'totalHasTax'
					},
					{
						name: '备注',
						label: 'remark'
					},
				],
				formData: {},
				// 清单明细
				column: [{
						label: '计划采购数量',
						key: 'planPurchaseQuantity'
					},
					{
						label: '含税单价',
						key: 'singleHasTax'
					},
					{
						label: '含税合计',
						key: 'productTotalHasTax'
					},
					{
						label: '备注',
						key: 'remark',
						slotName: 'remark'
					},
				],
				// 审批
				approvalForm: {
					type: "1",
					// 审批意见
					comment: '同意',
					// 退回节点key
					targetKey: "",
					// 任务id
					taskId: "",
					// 流程实例id
					instanceId: "",
					// 退回节点名称
					returnNodeName: "",
					variables: {}
				},
				showPicker: false,
				returnsList: [],
				rules: {
					type: [{
						required: true,
						message: '请选择审批结果',
						trigger: ['blur', 'change'],
						validator: checkApprovalType
					}],
					comment: [{
						required: true,
						message: '请输入审批意见',
						trigger: ['change'],
						validator: checkApprovalComment
					}],
					targetKey: [{
						required: true,
						message: '请选择退回节点',
						trigger: ['blur', 'change'],
						validator: checkApprovalTargetKey
					}],
				},
				// 退回节点时所用参数
				// 审批记录
				flowList: [],
				//获取节点信息
				stepActive: 1,
				showtaxRate: false,
				tax_rate: []
			}
		},
		async onLoad({
			id,
			fromTab,
			taskId
		}) {
			this.pageLoading = true
			this.fromTab = fromTab
			this.detailId = id
			this.approvalForm.taskId = taskId
			await this.getInfoById(this.detailId)
			//获取发票票类型
			await this.dicts('tax_rate').then(res => {
				this.tax_rate = [res.rows]
			})
			// this.setTeamInfo()
			await this.getApprovalRecords()
			if (this.fromTab == 0) {
				this.getReturnList()
			}
		},
		watch: {
			screenHeight(newHeight) {
				// 解决安卓底部固定部位被软键盘顶上去问题
				//监听屏幕高度变化  
				var f = document.getElementById("fixB")
				if (newHeight < this.originalHeight) {
					f.style.position = 'static';
				} else {
					f.style.position = 'fixed';
				}
			}
		},
		mounted() {
			//首次进入的原始高度
			const windowInfo = uni.getWindowInfo();
			this.originalHeight = windowInfo.windowHeight;
			uni.onWindowResize(this.watchResize);
		},
		methods: {
			taxRateShow(v) {
				if (v && uni.getStorageSync('userid').join(',').includes('wuzibujingli')) {
					this.showtaxRate = true
				}
			},
			//增值税率确定
			taxRate(v) {
				this.formData.vatRateDictLabel = v.value[0].dictLabel
				this.formData.vatRate = v.value[0].dictValue
				this.showtaxRate = false
			},
			//实时变化的窗口高度
			watchResize() {
				const windowInfo = uni.getWindowInfo();
				this.screenHeight = windowInfo.windowHeight;
			},
			successMethod(msg) {
				uni.showToast({
					title: msg,
					icon: 'none',
					duration: 2000
				})
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 2000)
			},
			// 请求字典
			dicts(type) {
				return new Promise((reslve, reject) => {
					this.$api.dict({
						pageNum: 1,
						pageSize: 999999,
						dictType: type
					}).then(res => {
						reslve(res)
					})
				})
			},
			// 获取部门
			async getDept(v) {
				let procurement;
				await this.dicts('material_procurement_plan').then(res => {
					procurement = res.rows.map(item => {
						return {
							label: item.dictLabel,
							value: item.dictValue,
						}
					})
				})
				let listItem = null
				if (v) {
					listItem = procurement.filter(item => {
						return item.label === v
					})
				} else {
					listItem = procurement.filter(item => {
						return item.label === this.deptName
					})
				}
				if (listItem && listItem.length) {
					this.approvalForm.variables.dept = listItem[0].value
				}
			},
			// 通过方法
			confirmComplete() {
				this.$api.postConfirmComplete(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			},
			// 退回方法
			confirmReturn() {
				this.$api.postConfirmReturn(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			},
			// 驳回方法
			confirmReject() {
				this.$api.getConfirmReject(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			},
			// 提交审批
			submitForm() {
				this.$refs.approvalForm.validate().then(valid => {
					if (valid) {
						if (uni.getStorageSync('userid').join(',').includes('wuzibujingli')) {
							if (this.formData.vatRateDictLabel != '') {
								this.$definition.update({
									...this.formData,
									isCirculation: false,
									isDraft: 0
								}).then(res => {
									if (res.code == 200) {
										switch (this.approvalForm.type) {
											case 1:
											case "1":
												// 通过
												this.confirmComplete();
												break;
											case 2:
											case "2":
												// 退回
												this.confirmReturn();
												break;
											case 3:
											case "3":
												// 驳回
												this.confirmReject();
												break;
										}
									} else {
										uni.showToast({
											icon: 'none',
											title: res.msg,
										})
									}
								})
							} else {
								uni.showToast({
									icon: 'none',
									title: '请选择税率',
								})
							}
						} else {
							switch (this.approvalForm.type) {
								case 1:
								case "1":
									// 通过
									this.confirmComplete();
									break;
								case 2:
								case "2":
									// 退回
									this.confirmReturn();
									break;
								case 3:
								case "3":
									// 驳回
									this.confirmReject();
									break;
							}
						}
					}
				})
			},
			// 退回节点选择
			confirmPicker(val) {
				this.approvalForm.returnNodeName = val.value[0].name
				this.approvalForm.targetKey = val.value[0].id
				this.showPicker = false
			},
			closePicker() {
				this.showPicker = false
			},
			nodeInputHandler() {
				this.showPicker = true
			},
			// 获取可退回节点
			getReturnList() {
				this.$api.getReturnList(this.approvalForm).then(res => {
					this.returnsList = []
					this.returnsList.push(res.data)
				})
			},
			groupChange(val) {
				this.approvalForm.type = val
				this.approvalForm.targetKey = ""
				this.approvalForm.returnNodeName = ""
				if (this.approvalForm.type == 3) {
					this.approvalForm.comment = '驳回'
					this.$refs.approvalForm.validate()
				} else if (this.approvalForm.type == 1) {
					this.approvalForm.comment = '同意'
					this.$refs.approvalForm.validate()
				} else {
					this.approvalForm.comment = ""
					// this.getReturnList()
				}
			},
			setTeamInfo() {
				this.mapData = new Map();
				this.mapData.set('业务单号', 'reviewCode')
				this.mapData.set('项目名称', 'projectName')
				this.mapData.set('物资类型', 'materialTypeDictLabel')
				this.mapData.set('采购时间', 'purchaseTime')
				this.mapData.set('增值税税率', 'vatRateDictLabel')
				this.mapData.set('含税合计', 'totalHasTax')
				this.mapData.set('备注', 'remark')
			},
			// 获取节点信息
			getApprovalNode(procInsId) {
				this.$definition.getApprovalNode(procInsId).then((res) => {
					if (res.code === 200) {
						this.stepActive = res.data.active
					}
				});
			},
			async getInfoById(id) {
				await this.$api.queryPurchaseDetailById(id).then(res => {
					this.formData = res.data
					this.getDept(res.data.createDeptName)
					//获取节点信息
					this.getApprovalNode(this.formData.procInsId)
				})
			},
			// 获取审批记录
			async getApprovalRecords() {
				let param = {
					procInsId: this.formData.procInsId,
					deployId: this.formData.deployId,
				};
				await this.$api.getApprovalRecords(param).then(res => {
					this.flowList = [...res.data.flowList]
					this.flowList = this.flowList.reverse()
					// this.approvalForm.taskId = res.data.flowList[0]?.taskId
					this.approvalForm.instanceId = this.formData.procInsId;
					this.pageLoading = false
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container-box {
		margin-top: 18rpx;
		padding-bottom: 160rpx;
	}

	.space {
		@include center-space()
	}

	.group-text ::v-deep uni-text.u-radio__text {
		font-size: 28rpx !important;
	}

	.approval-box {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #dee2eb;

		.approval-info {
			width: 600rpx;
		}

		.line-user {
			color: #B1B3B7;
			position: relative;
		}
	}

	.fs-28 {
		@include text-font-size(28rpx)
	}

	.fs-20 {
		@include text-font-size(20rpx)
	}

	.fix-btn {
		position: fixed;
		background-color: #fff;
		width: 100%;
		height: 160rpx;
		bottom: 0;

		::v-deep .u-button {
			margin: 34rpx auto;
			width: 694rpx;
			height: 92rpx;
			font-size: 28rpx;
		}
	}

	.approval-form {
		::v-deep .u-form-item__body {
			padding-top: 0;
		}

		::v-deep .u-form-item__body__right__message {
			margin-left: 0 !important;
		}
	}

	/* 折叠面板 */
	.collapse-box {
		::v-deep .u-cell {
			border-bottom: 2rpx solid #dee2eb;
		}

		::v-deep .u-cell__title-text,
		::v-deep .u-page__item__title__slot-title {
			font-size: 28rpx
		}

		::v-deep .u-collapse-item {
			border: 1px solid #dee2eb;
			border-radius: 8rpx;
		}

		::v-deep .u-collapse-item__content__text {
			padding-top: 0;
			padding-bottom: 0;
		}
	}

	.radio-flex,
	.uni-list-cell {
		display: flex;
	}

	.radio-flex {
		::v-deep uni-radio .uni-radio-input {
			width: 20px;
			height: 20px;
		}

		.uni-list-cell {
			margin-right: 10rpx;
		}
	}
</style>